import { MediaPlayer } from './mediaPlayer'
import type { MediaView } from '@/api/children.typing'

export class VideoPlayer extends MediaPlayer {
  // 视频特定状态
  videoContext: UniApp.VideoContext | null = null
  playbackRate = ref(1)
  expiredMediaIds = ref<Set<number>>(new Set())

  // 实现抽象方法
  play(item: MediaView, progressSeconds: number = 0) {
    this.playingItem.value = item
    this.duration.value = item.duration
    this.isPlaying.value = true

    if (!this.videoContext) {
      this.videoContext = uni.createVideoContext('hic-video')
    }
    this.videoContext.playbackRate(this.playbackRate.value)
    this.videoContext.seek(progressSeconds)
    this.videoContext.play()
  }

  pause() {
    if (this.videoContext) {
      this.videoContext.pause()
      this.isPlaying.value = false
    }
  }

  resume() {
    if (this.videoContext) {
      this.videoContext.play()
      this.isPlaying.value = true
    }
  }

  stop() {
    if (this.videoContext) {
      this.videoContext.pause()
      this.videoContext = null
    }
    this.playingItem.value = null
    this.isPlaying.value = false
  }

  // 视频特定方法
  setVideoContext(context: UniApp.VideoContext) {
    this.videoContext = context
  }

  handleTimeUpdate(currentTime: number) {
    this.currentTime.value = currentTime
    const now = Date.now()
    if (now - this.lastSaveTime > this.SAVE_INTERVAL && this.playingItem.value) {
      this.savePlaybackProgress(this.playingItem.value.id, currentTime)
      this.lastSaveTime = now
    }
  }

  handleLoadedMetadata(duration: number) {
    this.duration.value = duration
  }

  // 检查媒体过期状态
  checkMediaExpiration(item: MediaView) {
    if (this.expiredMediaIds.value.has(item.id)) return true

    const now = Date.now()
    if (item.expirationDate && now > item.expirationDate) {
      this.expiredMediaIds.value.add(item.id)
      return true
    }

    return false
  }
}
